<?php

namespace control;
/*
*外购产品需求表类
*/

class purchaseDemandClass extends adIndexClass
{
    private const page = 'purchaseDemand';
    private const title = '外购产品需求表';

    /**
     * 字段初始化
     */
    public function fieldInit($fun): array
    {
        switch ($fun) {
            default:
                $tr = [
                    'supplier'      => [
                        'name'  => '供应商',
                        'width' => 180,
                    ],
                    'sourceDate'    => [
                        'name'  => '单据日期',
                        'width' => 100,
                        'sort'  => 1,
                    ],
                    'sourceType'    => [
                        'name'  => "源单类型",
                        'width' => 100,
                    ],
                    'sourceNo'      => [
                        'name'  => "源单号",
                        'width' => 150,
                        'sort'  => 1,
                    ],
                    'subject'       => [
                        'name'  => '存货类别',
                        'width' => 100,
                    ],
                    'code'          => [
                        'name'  => '物料编码',
                        'width' => 150,
                        'sort'  => 1,
                    ],
                    'materialName'  => [
                        'name'  => '物料名称',
                        'width' => 100,
                    ],
                    'model'         => [
                        'name'  => '规格型号',
                        'width' => 100,
                        'sort'  => 1,
                    ],
                    'unit'          => [
                        'name'  => '单位',
                        'width' => 100,
                    ],
                    'text'          => [
                        'name'  => '备注',
                        'width' => 100,
                    ],
                    'num'           => [
                        'name'  => '订单数量',
                        'width' => 100,
                        'sort'  => 1,
                    ],
                    'stockNum'      => [
                        'name'  => '库存数量',
                        'width' => 100,
                    ],
                    'purchaseNum'   => [
                        'name'  => '已采购数量',
                        'width' => 100,
                    ],
                    'residue'       => [
                        'name'  => '剩余待采购',
                        'width' => 100,
                    ],
                    'source'        => [
                        'name'  => '来源',
                        'width' => 100,
                    ],
                    'supplyControl' => [
                        'name'  => '供应控制',
                        'width' => 200,
                    ]
                ];
        }
        return $tr;
    }

    /*列表页-查询条件*/
    public function homeOptions($isAsync = true)
    {
        $material = new materialClass();
        //生成查询表单
        $html = $this->tableShow([
            [
                [
                    "状态" => checkbox(array('name' => 'isClear', 'value' => ['未清', '已清'], 'checked' => ['未清']))
                ],
                [
                    "源单编号" => text(array("name" => "orderNo")),
                    "存货类别" => select(array('name' => 'subject', 'option' => $material->checkOption)),
                    '物料编码' => text(array("name" => "code")),
                ],
                [
                    '物料名称' => text(array("name" => "materialName")),
                    '来源'   => select(array('name' => 'source', 'option' => $material->sourceOption)),
                    "供应控制" => select(array('name' => 'supplyControl', 'option' => $material->controlOption)),
                ],
                [
                    "供应商"  => supplierClass::supplierSelect(array('title' => '')),
                    "单据日期" => text(array("name" => "createTime", 'laydate' => ['type' => 'date', 'range' => '~'])),
                ]
            ]
        ], 1);
        //返回
        if (!$isAsync) {
            return $html;
        } else {
            return json_encode(['html' => $html], 320);
        }
    }

    /*列表-查询条件*/
    public function home()
    {
        $html = $this->homeOptions(false);
        //控件
        $button = '';
        if ($this->power(self::page, 'edit')) {
            $button = "<span class='spanButton' onclick=\"purchaseApply()\">生成采购申请</span>";
            $button .= "<span class='spanButton' onclick=\"commitOrder()\">生成采购订单</span>";
            $button .= "<span class='spanButton' onclick=\"layer('" . self::page . "','mark','listForm')\">标记为已清</span>" . componentClass::tipComponent('采购数量已经满足销售数量可标记为已清');//采购数量是否已经满足了销售单数量要求
        }
        //返回
        return $this->homeFun($this->search($html, layout: 'pop', toolButton: $button)) . $this->js();
    }

    /*客户列表-查询结果*/
    public function homeSearch()
    {
        //like查询数组
        $like = array(
            "a.sourceNo"      => $this->post('orderNo'),//证件编号
            "c.name"          => $this->post('materialName'),
            "c.code"          => $this->post('code'),
            'c.supplyControl' => $this->post('supplyControl')
        );
        //全等查询数组
        $equal = array(
            "c.subject"    => $this->post('subject'),
            "c.source"     => $this->post('source'),
            "a.coid"       => self::$coid,
            "a.supplierId" => $this->post('supplierId'),
        );
        $and   = '';
        if ($this->post('createTime')) {
            //单据日期
            $and .= self::timeComparison($this->post('createTime'), field: 'a.sourceDate');
        }
        if ($this->post('isClear')) {
            $isClear = [];
            if (in_array('已清', $this->post('isClear'))) {
                $isClear[] = 1;
            }
            if (in_array('未清', $this->post('isClear'))) {
                $isClear[] = 0;
            }
            //单据日期
            $and .= " and isClear in ('" . implode("','", $isClear) . "')";
        }
        //排序
        $orderBy = $this->listSort(array(
            "search" => $this->post('list_sort_key') ?: 'a.sourceDate desc,a.list',
            "sort"   => $this->post('list_sort') ?: "asc",
            "array"  => array(),
        ));
        //获取查询结果
        $where = search(array("like" => $like, "=" => $equal)) . $and;
        $page  = $this->page(array(
            "table" => "purchase_demands as a join material as c on c.id = a.materialId",
            'field' => "a.*,c.code,c.name as materialName,c.model,c.subject,c.source,c.supplyControl",
            "where" => $where,
            "order" => $orderBy['orderBy']
        ));
        //获取自定义字段参数
        $installSearch = $this->installSearch();
        $body          = [];
        //表格控件区
        $liButton = array(
            $this->checkAll("listForm", "listId")
        );
        //获取记录
        foreach ($page['array'] as $array) {
            //列表控件
            $dominate = array(
                "box" => array("name" => "listId", "value" => $array['id']),
            );
            //已采购数量
            $purchaseNum = find(array(
                'table'  => "purchase_order as a join purchase_order_detail as b on a.id = b.orderId",
                'single' => "a.state = '已确认' and b.sourceId = '$array[id]'",
                'field'  => "ifnull(sum(b.num),0) as num"
            ))['num'];
            //$supplierSelect = "<div class='search '>".selectMultiple(array('name'=>'supplierId','class'=>'width200','title'=>'供应商','change'=>'setSupplier','value'=>$array['supplierId'],'table'=>"supplier",'where'=>"coid = '".self::$coid."'",'sqlId'=>'id','sqlField'=>'name'))."</div>";
            $liButton[] = $this->dominate($dominate);
            //本行初始化
            $row = [];
            foreach ($installSearch['key'] as $key) {
                switch ($key) {
                    case "text":
                        $sourceInfo = query($array['sourceTable'], "id = '$array[sourceId]'");
                        $row[]      = $sourceInfo['text'] ?? '';
                        break;
                    case "num":
                        $row[] = self::lostZero($array['num'], 'numPrecision');
                        break;
                    case "stockNum":
                        $stockNum = inventoryBalanceClass::inventoryNum($array['materialId']);//库存数量
                        $row[]    = self::lostZero($stockNum, 'numPrecision');
                        break;
                    case "purchaseNum":
                        $row[] = self::lostZero($purchaseNum, 'numPrecision');
                        break;
                    case "residue":
                        $row[] = $array['num'] - $purchaseNum;
                        break;
                    case "supplier":
                        $supplier       = query('supplier', "id = '$array[supplierId]'");
                        $supplierSelect =
                            "<div class='search-list'>" .
                            componentClass::selectText(array(
                                'name'      => 'supplierId[]',
                                'value'     => $array['supplierId'],
                                'class'     => 'list-text width150',
                                'title'     => $supplier['name'],
                                'change'    => "setSupplier($(e).siblings('input'))",
                                'cla'       => self::page,
                                'fun'       => 'getSupplier'
                            )) .
                            "</div>";
                        $row[]          = $supplierSelect;
                        break;
                    default:
                        $row[] = isset($array[$key]) && $array[$key] ? $array[$key] : '';
                }
            }
            $body[] = $row;
        }
        $numTotal = find([
            'table'  => "purchase_demands as a join material as c on c.id = a.materialId",
            'single' => $where,
            'field'  => "ifnull(sum(a.num),0) as num",
        ]);
        //已采购数量
        $purchaseNum = find(array(
            'table'  => "purchase_order as main join purchase_order_detail as detail on main.id = detail.orderId",
            'single' => "main.state = '已确认' and detail.sourceId in (select a.id from purchase_demands as a join material as c on c.id = a.materialId where 1=1 {$where})",
            'field'  => "ifnull(sum(detail.num),0) as num"
        ))['num'];
        $total       = [
            'num'         => self::lostZero($numTotal['num'], 'numPrecision'),
            'purchaseNum' => self::lostZero($purchaseNum, 'numPrecision'),
            'residue'     => self::lostZero($numTotal['num'] - $purchaseNum, 'numPrecision'),
        ];
        //生成页面
        $li = $this->li(array(
            "body"        => $body,
            "install"     => $installSearch,
            "button"      => array("html" => $liButton),
            "orderBySign" => $orderBy,
            "page"        => $page['para'],
            "total"       => $total,
        ));
        //返回
        $json['html'] = "<form name='listForm' class='listPage'>" . $li . "</form>" . $page['button'] . clear;
        return json_encode($json, 320);
    }

    /**
     * 供应商模糊查询
     * @return false|string
     */
    public function getSupplier()
    {
        $val          = $this->post('keyword');//关键词
        $json['data'] = [];
        $where        = "";
        if ($val) {
            $where .= " and (name like '%$val%' or code like '%$val%')";
        }
        $all = find(array('table' => 'supplier', 'where' => "coid = '" . self::$coid . "' $where  order by code asc limit 50"));
        foreach ($all['array'] as $array) {
            $json['data'][] = array('title' => $array['name'], 'code' => $array['code'], 'id' => $array['id']);
        }
        $json['warn'] = 2;
        return json_encode($json, 320);
    }

    public function mark(): bool|string
    {
        //生成表单
        $html = $this->layerEdit(array("table" => array(
            array(
                "提示：" => "是否标记所选数据为已清？",
            ),
        )));
        //返回
        return $this->layer(array("title" => "提示", "height" => 165, "html" => $html, 'formTwo' => 'listForm'));
    }

    public function markEdit(): bool|string
    {
        $listId = $this->post('listId');
        if (static::is_null_array($listId)) {
            $json['warn'] = '请选择数据';
        } elseif (!$this->power(self::page, 'edit')) {
            $json['warn'] = '您还没有' . self::title . '的编辑权限';
        } else {
            $x    = 0;
            $text = '';
            foreach ($listId as $id) {
                $purchase_demands = query('purchase_demands', "id = '$id'");
                $warn             = update(array('table' => 'purchase_demands', 'field' => ['isClear' => 1], 'where' => "id = '$id'"));
                $material         = query('material', "id = '$purchase_demands[materialId]'");
                if ($warn == '更新成功') {
                    $x++;
                    $text .= "外购需求【{$purchase_demands['id']}】,产品【{$material['code']}-{$material['name']}-{$material['model']}】标记为已清<br>";
                } else {
                    $text .= "外购需求【{$purchase_demands['id']}】,产品【{$material['code']}-{$material['name']}-{$material['model']}】标记已清失败<br>";
                }
            }
            $text = $this->control['name'] . '标记了外购需求如下：' . $text;
            $this->logText(["type" => self::page, "text" => $text]);
            $json['warn']     = 2;
            $_SESSION['warn'] = "成功标记了{$x}条数据";
        }
        return json_encode($json, 320);
    }

    /**
     * 判断勾选的数据是否是同一个供应商下的
     * @return bool|string
     */
    public function createPurchaseOrderEdit(): bool|string
    {
        $listId = $this->post('listId');
        if (static::is_null_array($listId)) {
            $json['warn'] = '请选择需要生成采购订单的物料';
        } else {
            $preSupplierId = '';
            foreach ($listId as $id) {
                $saleOrderDetail = query('sale_order_detail', "id = '$id'");
                if ($saleOrderDetail['supplierId'] && $preSupplierId && $saleOrderDetail['supplierId'] != $preSupplierId) {
                    $json['warn'] = "请选择供应商相同的数据";
                    break;
                }
                $preSupplierId = $saleOrderDetail['supplierId'];
            }
            if (!isset($json['warn']) || empty($json['warn'])) {
                $json['warn'] = 2;
            }
        }
        return json_encode($json, 320);
    }

    public function js(): string
    {
        return <<<eof
<script>
//设置供应商
function setSupplier(e){
    let supplierId = $(e).val();
    let id = $(e).parent().parent().parent().parent().find("[name='listId[]']").val();
    $.post(root+'control/adIndex.html?cla={$this->get('cla')}&fun=setSupplier',{supplierId:supplierId,id:id},function(res) {
        if (res.warn !=2){
            warn(res.warn,'error');
        }
    },'json')
}

function commitOrder(){
     cxDialog('是否确认生成采购单?', () => {
          $.post(root+'control/adIndex.html?cla={$this->get('cla')}&fun=createPurchaseOrderEdit',$("[name='listForm']").serialize(),function(res) {
                if (res.warn !=2){
                    warn(res.warn,'error');
                }else{
                    let arr = [];
                $("[name='listForm'] input[type=checkbox]:checked").each(function () {
                    if ($(this).val() && $(this).val() !== 'on') {
                        arr.push($(this).val());
                    }
                });
                let listId = arr.join(",");
                newIframe('采购订单',root+'control/adIndex.html?cla=purchaseOrder&fun=edit&source=demand&listId='+listId,'供应链','采购')
                }
          },'json')
                
        }, () => {
          // click no callback
        });
}

function purchaseApply(){
    cxDialog('是否确认生成采购申请?', () => {
                let arr = [];
                $("[name='listForm'] input[type=checkbox]:checked").each(function () {
                    if ($(this).val() && $(this).val() !== 'on') {
                        arr.push($(this).val());
                    }
                });
                let listId = arr.join(",");
                if (!listId){
                    msg('请选择数据','error');
                }else{
                    newIframe('采购申请',root+'control/adIndex.html?cla=purchaseApply&fun=edit&source=purchaseDemand&listId='+listId,'供应链','采购')
                }
        }, () => {
          // click no callback
        });
}
</script>
eof;

    }

    /**
     * 设置供应商ID
     * @return bool|string
     */
    public function setSupplier(): bool|string
    {
        $supplierId = $this->post('supplierId');//供应商ID
        $id         = $this->post('id');//销售明细ID
        $warn       = static::update(array('table' => 'purchase_demands', "field" => ['supplierId' => $supplierId], 'where' => "id = '$id'"));
        if ($warn != '更新成功') {
            $json['warn'] = '设置失败';
        } else {
            $json['warn'] = 2;
            $text         = $this->control['name'] . '设置了外购产品需求【' . $id . '】的供应商ID:' . $supplierId;
            $this->logText(["type" => self::page, "text" => $text]);
        }
        return json_encode($json, 320);
    }

}
